(function(){
	//record changed category names between every two save event
	var idToDelete,
		arrayChangedName = new Array(), 
		iconPlusClass = ".icon-plus";
		iconMinusClass = ".icon-minus";
		iconSaveClass = ".btn-save";
		iconDisplayClass = ".dd-display";
	
	//add a new product
	$(document).on("click", iconPlusClass,function(){
		 $('#nestable_list_1').nestable('addNewElement', arrayChangedName);
	});

	//delete a product
	$(document).on("click", iconMinusClass,function handle(){
        
		swal({
				title: "确定要删除",
				text: "真的要删除吗？删除后分类无法恢复！",
				type: "warning",
				showCancelButton: true,
				confirmButtonColor: "#DD6B55",
				confirmButtonText: "继续删除",
				cancelButtonText: "取消",
				closeOnConfirm: false 
			}, 
			function(){
				swal("删除成功", "可以继续编辑了", "success"); 
				idToDelete = $('#nestable_list_1').nestable('removeElement');
				$.ajax({ 
					data:  {
					  id:idToDelete,   
					},
					type : "POST",
					url:"/app_admin/handle_product_category_delete/",
					error:function(result){  
						//upload tree ajax failed
						//info user to continue editing or save again
						// swal("继续执行删除", "尝试上一次删除内容", "warning"); 
						//deleted already, append ajax to server again
						handle();
					},
					success:function(result){
						swal('删除成功');
					}  
				});
		});        
	});

	//when category name changed, the new name will be save to array change name
	$(iconDisplayClass).watch(function(value, e){
		updateArrayCategory(value, e, arrayChangedName);
	});

	//when click save button, send tree JSON and images to server
	$(document).on("click", iconSaveClass,function handle(){
		var i, data, items,
			 listNodeName = 'ol',
			 itemNodeName = 'li',
			 inputNodeName = 'input',
			 list = $('#nestable_list_1'),
			 bImageUpload = false;
		
		//check if there is new info to be save and upload
		items = list.find(itemNodeName);
		items.each(function(){
			var li = $(this),
				fileInputEl = li.find(inputNodeName).first();
				
			if (fileInputEl.val()){
				bImageUpload = true;
				return false;
			}
		});	
		if (arrayChangedName.length == 0 && bImageUpload == false){
			swal('没有任何改动','请继续编辑分类','warning');
			return;
		}
		

		//output whole category tree JSON
		if (window.JSON) {
			data  = window.JSON.stringify(list.nestable('serialize', arrayChangedName)); 
		} else {
			data ='JSON browser support required for this demo.';
		}
        
		$.ajax({ 
			async: false,
			type : "POST",
		//    dataType : 'Text', 
			contentType : 'application/json',
			url:"/app_admin/handle_product_category_update_post/",
			data : data,
			 
			error:function(result){ 
				//upload tree ajax failed
				//info user to continue editing or save again
				swal({
						title: "保存失败",
						text: "是否要重新保存？如果取消可以继续编辑。",
						type: "warning",
						showCancelButton: true,
						confirmButtonColor: "#DD6B55",
						confirmButtonText: "继续保存",
						cancelButtonText: "取消",
						closeOnConfirm: false 
					},
					function(){
						// swal("继续保存", "尝试上一次保存内容", "warning"); 
						//deleted already, append ajax to server again
						handle();
				});					
			},
			 
			success:function(result){
				var strJson =result,
					 elHandle,
					 str4UploadId='uploadImgId',
					 listJson = eval("("+strJson+")");

				items.each(function(){
					var inputId, item,
						li = $(this),
						fileInputEl = li.find(inputNodeName).first();
						 
					//update category ID from server before upload images
					for (var i=0; i< listJson.length; i++){
						for (var key in listJson[i]){
							if (li.data("id") == key){
								//update data-id in li element
								li.data("id", listJson[i][key]);
								//update id in input of class="dd-file"
								li.children(".dd-file").attr("id", str4UploadId + listJson[i][key]);
							}
						}
					} 
					
					//reset the arrayChangedName to empty array
					arrayChangedName = Array();
					//if no image to be upload
					if (bImageUpload == false){
						swal('保存成功','请继续编辑分类','success');
					}
					
					item = $.extend({}, li.data());
					if (fileInputEl.val()){
						//item.children = fileInputEl.val();  
						inputId = fileInputEl.attr("id");
						
						//write sth pls
						data={'id':item['id']};
                        data['table_class']='ProductClass';
						$("#lodingId"+item['id']).show();
						ajaxFileUpload(inputId,data);
					}

					//ajax to upload image
					function ajaxFileUpload(fileElementId,data) {
						 var url="/upload_image";
						 $.ajaxFileUpload
						 (
							  {
									url: url, //用于文件上传的服务器端请求地址
									type: 'post',
									data: data, //此参数非常严谨，写错一个引号都不行
									secureuri: false, //一般设置为false
									fileElementId: fileElementId, //文件上传空间的id属性  <input type="file" id="file" name="file" />
									dataType: 'json', //返回值类型 一般设置为json
									success: function (data, status)  //服务器成功响应处理函数
									{
										 if (typeof (data.error) != 'undefined') {
											  if (data.error != '') {
													swal('保存失败','请保存以下信息，反馈给供应商：' + data.error,'error');
											  } else {
													//alert(data.msg);
													swal('保存成功','请继续编辑分类','success');
											  }
										 }
										 
										 $("#lodingId"+item['id']).hide();
									},
									error: function (data, status, e)//服务器响应失败处理函数
									{
										swal('保存失败','请保存一下信息，反馈给供应商：' + data.error,'error');
										// $("#lodingId"+item['id']).hide();
									}
							  }
						 ) 
						 return false;
					}    
				});
			}
		});
	});
})();
